package com.luyuan.crm.sale.web.converter;

import javax.annotation.Resource;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.springframework.stereotype.Component;

import com.luyuan.crm.product.model.Product;
import com.luyuan.crm.product.service.ProductService;
import com.ruijie.util.StringUtils;

@Component("productConverter")
public class ProductConverter implements Converter {
    @Resource(name = "productService")
    private ProductService productService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (StringUtils.isNullOrEmpty(value)) {
            return null;
        }

        Product product = productService.findUniqueBy("name", value.substring(value.indexOf("_") + 1));
        return product;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        Product product = (Product) value;
        if (product == null) {
            return null;
        }

        return product.getAbbreviation() + "_" + product.getName();
    }
}
